package com.dmgis.qxfw.dataservice.businessservice.common.util;

import com.dmgis.qxfw.dataservice.commonservice.utils.MD5Utils;
import com.dmgis.qxfw.dataservice.commonservice.utils.RedisUtil;
import org.apache.commons.lang3.RandomStringUtils;
import redis.clients.jedis.Jedis;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 @ClassName TokenProccessor
 @Description TODO
 @Author sun
 @Date 2020/4/26 9:59
 @Version 1.0
 **/
public class TokenProccessor {

    /**
     * 生成Token
     * @return
     */
    public String generateToken(String userName) {
        //userName+时间戳+随机字符串 MD5加密
        long currentTime = System.currentTimeMillis();
        //生成指定长度的随机字符串
        String randomStr = RandomStringUtils.randomAlphanumeric(10);
        StringBuilder encodeStr = new StringBuilder();
        encodeStr.append(userName).append(currentTime).append(randomStr);
        //使用Md5加密生成token
        String token = MD5Utils.MD5Encode(encodeStr.toString(), "utf-8");
        //将token存储到redis并且设置过期时间为3小时
        Jedis jedis = RedisUtil.getJedis();
        jedis.set(token,Long.toString(System.currentTimeMillis()), "NX","EX", 3*3600);
        return token;
    }
}
